package com.offcn.webui.controller;

import com.offcn.dycommon.response.AppResponse;
import com.offcn.webui.service.MemberServiceFeign;
import com.offcn.webui.service.ProjectServiceFeign;
import com.offcn.webui.vo.resp.ProjectVo;
import com.offcn.webui.vo.resp.UserRespVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
@Slf4j
public class DispathcherController {

    @Autowired
    private MemberServiceFeign memberServiceFeign;

    @Autowired
    private ProjectServiceFeign projectServiceFeign;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 首页跳转
     *
     * @Description
     */
    @RequestMapping("/")
    public String toIndex(Model model) {
        System.out.println("-----------------------");
        //从redis中读取项目集合
        List<ProjectVo> data = (List<ProjectVo>) redisTemplate.opsForValue().get("projectStr");
        //redis项目集合为空,调用项目服务,读取全部项目
        if (data == null) {
            AppResponse<List<ProjectVo>> allProject = projectServiceFeign.all();
            data = allProject.getData();

            redisTemplate.opsForValue().set("projectStr", data);
        }
        model.addAttribute("projectList", data);
        return "index";
    }

    /**
     * 用户登录
     * @param loginacct
     * @param password
     * @param session
     * @return
     */
    @RequestMapping("/doLogin")
    public String doLogin(String loginacct, String password, HttpSession session) {
        AppResponse<UserRespVo> appResponse = memberServiceFeign.login(loginacct, password);
        UserRespVo userRespVo = appResponse.getData();
        log.info("登录账号:{},密码{}", loginacct, password);
        log.info("登录用户数据:{}", userRespVo);
        if (userRespVo == null) {
            //账号不存在,重定向到登录页面
            return "redirect:/login.html";
        }

        //用户信息存储到session
        session.setAttribute("SessionMember", userRespVo);
        //从session中获取前缀
        String preUrl = (String) session.getAttribute("preUrl");
        //如果前缀不存在,跳转到默认首页
        if (StringUtils.isEmpty(preUrl)) {
            return "redirect:/";
        }
        return "redirect:/" + preUrl;

    }





}
